import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from flask_wtf.csrf import CSRFProtect, generate_csrf
from config import config_dict
from info.utils.commons import news_hot_filter

redis_store = None
db=SQLAlchemy()

def create_app(config_name, ):
    app = Flask(__name__)
    Config = config_dict.get(config_name)
    #初始化日志级别
    log_file(Config.LEVEL_NAME)
    app.config.from_object(Config)

    # 创建SQLAlchemy对象,关联app
    # global db
    db.init_app(app)



    # 创建redis对象
    global redis_store
    redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, decode_responses=True)

    # 创建Session对象,读取APP中session配置信息
    Session(app)

    # 使用CSRFProtect保护app
    CSRFProtect(app)
    # 将蓝图注册到app
    # 解决循环导包
    from info.modules.index import index_blueprint
    from info.modules.passport import  passport_blue
    from  info.modules.news import  news_blue
    from info.modules.profile import profile_blue
    app.register_blueprint(index_blueprint)
    app.register_blueprint(passport_blue)
    app.register_blueprint(news_blue)
    app.register_blueprint(profile_blue)
    #添加自定义过滤器
    app.add_template_filter(news_hot_filter,"my_filter")
    @app.after_request
    def after_request(resp):
        csrf_token=generate_csrf()
        resp.set_cookie("csrf_token",csrf_token)
        return  resp
    return app


def log_file(LEVEL_NAME):
    # 设置日志的记录等级
    logging.basicConfig(level=LEVEL_NAME)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("info/logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)
